Google analytics js

jamesperet 9 years ago
parent
commit
b9c59939a9
2 changed files with 44 additions and 0 deletions
  1. 1 0
      app/assets/javascripts/application.js
  2. 43 0
      app/assets/javascripts/google_analytics.js.coffee

+ 1 - 0
app/assets/javascripts/application.js

@@ -17,4 +17,5 @@
17 17
 //= require jasny-bootstrap
18 18
 //= require summernote
19 19
 //= require turbolinks
20
+//= require google_analytics
20 21
 //= require_tree .

+ 43 - 0
app/assets/javascripts/google_analytics.js.coffee

@@ -0,0 +1,43 @@
1
+class @GoogleAnalytics
2
+
3
+  @load: ->
4
+    # Google Analytics depends on a global _gaq array. window is the global scope.
5
+    window._gaq = []
6
+    window._gaq.push ["_setAccount", GoogleAnalytics.analyticsId()]
7
+
8
+    # Create a script element and insert it in the DOM
9
+    ga = document.createElement("script")
10
+    ga.type = "text/javascript"
11
+    ga.async = true
12
+    ga.src = ((if "https:" is document.location.protocol then "https://ssl" else "http://www")) + ".google-analytics.com/ga.js"
13
+    firstScript = document.getElementsByTagName("script")[0]
14
+    firstScript.parentNode.insertBefore ga, firstScript
15
+
16
+    # If Turbolinks is supported, set up a callback to track pageviews on page:change.
17
+    # If it isn't supported, just track the pageview now.
18
+    if typeof Turbolinks isnt 'undefined' and Turbolinks.supported
19
+      document.addEventListener "page:change", (->
20
+        GoogleAnalytics.trackPageview()
21
+      ), true
22
+    else
23
+      GoogleAnalytics.trackPageview()
24
+
25
+  @trackPageview: (url) ->
26
+    unless GoogleAnalytics.isLocalRequest()
27
+      if url
28
+        window._gaq.push ["_trackPageview", url]
29
+      else
30
+        window._gaq.push ["_trackPageview"]
31
+      window._gaq.push ["_trackPageLoadTime"]
32
+
33
+  @isLocalRequest: ->
34
+    GoogleAnalytics.documentDomainIncludes "local"
35
+
36
+  @documentDomainIncludes: (str) ->
37
+    document.domain.indexOf(str) isnt -1
38
+
39
+  @analyticsId: ->
40
+    # your google analytics ID(s) here...
41
+    'UA-58359004-1'
42
+
43
+GoogleAnalytics.load()